package se.plingapp.enterprisebeans;

import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import se.plingapp.entitybeans.Message;
import se.plingapp.entitybeans.User;

/**
 * Message business.
 *
 * @author Jens Ljungblad
 */
@Stateless
public class MessageFacade extends AbstractFacade<Message> {

    /**
     * Entity manager with a given persistence context.
     */
    @PersistenceContext(unitName = "PlingPU")
    private EntityManager em;

    /**
     * Implemented method from abstract facade.
     */
    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    /**
     * Constructor.
     */
    public MessageFacade() {
        super(Message.class);
    }

    /**
     * Find all messages by a given user.
     *
     * @param user
     */
    public List<Message> findByUser(User user) {
        Query q = em.createQuery("SELECT m FROM Message m WHERE m.user = :user ORDER BY m.id DESC", Message.class);
        q.setParameter("user", user);
        return q.getResultList();
    }

    /**
     * Find message feed of a given user. The message feed contains messages
     * from the user itself and the user's friends.
     *
     * @param user
     */
    public List<Message> findMessageFeedByUser(User user) {
        Query q = em.createQuery("SELECT m FROM Message m WHERE m.user = :user ORDER BY m.id DESC", Message.class);
        q.setParameter("user", user);
        return q.getResultList();
    }
}
